import { RouteRecordRaw, useRouter } from "vue-router";
import { defineStore } from "pinia";
import { constantRoutes } from "@/router";
import { store } from "@/store";
import { reqMultiRoles } from "@/api/business/menu";
import { useStorage } from "@vueuse/core";

const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");
const router = useRouter();

/**
 * 递归过滤有权限的异步(动态)路由
 *
 * @param routes 接口返回的异步(动态)路由
 * @returns 返回用户有权限的异步(动态)路由
 */
const filterAsyncRoutes = (routes: RouteRecordRaw[]) => {
  const asyncRoutes = <any>[];
  if (routes.length) {
    routes.forEach((route) => {
      const tmpRoute = { ...route }; // ES6扩展运算符复制新对象
      // tmpRoute.path = route.children?.length ? `/${route.url}` : route.url;
      tmpRoute.path = `/${route.url}`;
      tmpRoute.meta = {
        icon: route.icon,
        title: route.name,
      };
      tmpRoute.selected = false;
      const component = modules[`../../${tmpRoute.filePath}`];
      if (
        tmpRoute.level == 1 &&
        tmpRoute.children &&
        tmpRoute.children.length
      ) {
        tmpRoute.component = Layout;
      } else {
        tmpRoute.component = component;
      }

      if (tmpRoute.children && tmpRoute.children.length) {
        tmpRoute.children = filterAsyncRoutes(tmpRoute.children);
      }

      asyncRoutes.push(tmpRoute);
    });
  }
  return asyncRoutes;
};

// setup
export const usePermissionStore = defineStore("permission", () => {
  const pinia_menuList = ref<RouteRecordRaw[]>([]);

  // 当前菜单的按钮权限
  const pinia_curMenuInfo = useStorage("pinia_curMenuInfo", {});
  // 设置按钮权限
  function setCurMenuInfo(val: {}) {
    pinia_curMenuInfo.value = val;
  }

  function setRoutes(newRoutes: RouteRecordRaw[]) {
    pinia_menuList.value = constantRoutes.concat(newRoutes);
  }
  /**
   * 生成动态路由
   *
   * @param roles 用户角色集合
   * @returns
   */
  function generateRoutes(roles: any[]) {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      // 接口获取所有路由
      reqMultiRoles({ roles }).then((res) => {
        if (res.code == 1) {
          const accessedRoutes = filterAsyncRoutes(res.data);
          setRoutes(accessedRoutes);
          resolve(accessedRoutes);
        }
      });
    });
  }

  /**
   * 混合模式左侧菜单
   */
  const mixLeftMenu = ref<RouteRecordRaw[]>([]);
  function getMixLeftMenu(activeTop: string) {
    pinia_menuList.value.forEach((item) => {
      if (item.path === activeTop) {
        mixLeftMenu.value = item.children || [];
      }
    });
  }
  return {
    pinia_menuList,
    setRoutes,
    generateRoutes,
    getMixLeftMenu,
    mixLeftMenu,
    pinia_curMenuInfo,
    setCurMenuInfo,
    filterAsyncRoutes,
  };
});

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
